package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.ZtreeNew;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.SysUserMsg;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserMsgMapper;
import com.ruoyi.system.service.ISysNoticeService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.web.websocket.MyWebSocketHandler;

/**
 * 公告 信息操作处理
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {
	private String prefix = "system/notice";

	@Autowired
	private ISysNoticeService noticeService;
	@Autowired
	private ISysRoleService roleService;
	@Autowired
	private MyWebSocketHandler myWebSocketHandler;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private SysUserMsgMapper sysUserMsgMapper;

	@RequiresPermissions("system:notice:view")
	@GetMapping()
	public String notice() {
		return prefix + "/notice";
	}

	@GetMapping("/msg")
	public String msg() {
		return prefix + "/noticeN";
	}
	/**
	 * 查询公告列表
	 */
	@RequiresPermissions("system:notice:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysNotice notice) {
		startPage();
		List<SysNotice> list = noticeService.selectNoticeList(notice);
		return getDataTable(list);
	}
	@PostMapping("/listN")
	@ResponseBody
	public TableDataInfo listN(SysNotice notice) {
		notice.setUserId(ShiroUtils.getUserId());
		startPage();
		List<SysNotice> list = noticeService.selectNoticeListN(notice);
		if (list != null && list.size() > 0) {
			for (SysNotice sysNotice : list) {
				if (sysNotice.getNoticeId() == null ) {
					sysNotice.setNoticeTitle("库存预警");
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 新增公告
	 */
	@GetMapping("/add")
	public String add() {
		return prefix + "/add";
	}

	/**
	 * 新增保存公告
	 */
	@RequiresPermissions("system:notice:add")
	@Log(title = "通知公告", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(SysNotice notice) {
		notice.setCreateBy(ShiroUtils.getLoginName());
		notice.setNoticeType("1");
		List<SysUserMsg> alList = noticeService.insertNotice(notice);
		if (alList != null && alList.size() > 0) {
			for (SysUserMsg sysUserMsg : alList) {
				myWebSocketHandler.sendInfo(sysUserMsg.getUserId().toString(), "有公告了");;
			}
		}
		return toAjax(1);
	}

	@GetMapping("/peopleRoleTreeData")
	@ResponseBody
	public List<ZtreeNew> peopleRoleTreeData( Integer noticeId) {
		SysRole role = new SysRole();
		// 先查询全部角色
		role.setNoticeId(noticeId);
		List<SysRole> list = roleService.selectRoleNoticeList(role);
		List<ZtreeNew> initZtree = initZtree(list);
		List<ZtreeNew> initZtree2 = new ArrayList<>();
		for (ZtreeNew ztree : initZtree) {
			String id = ztree.getId();
			List<SysUser> selectUserByRoleId = sysUserMapper.selectUserByRoleId(new Long(id),noticeId);
			for (SysUser sysUser : selectUserByRoleId) {
				ZtreeNew a = new ZtreeNew();
				a.setId(sysUser.getUserId()+"-u");
				a.setpId(id);
				if (sysUser.getnId() != null ) {
					a.setChecked(true);
				}
			    a.setName(sysUser.getLoginName());
	            a.setTitle(sysUser.getLoginName());
	            initZtree2.add(a);
			}
			
		}
		initZtree.addAll(initZtree2);
		return initZtree;
	}
	
    public List<ZtreeNew> initZtree(List<SysRole> list )
    {
        List<ZtreeNew> ztrees = new ArrayList<ZtreeNew>();
        for (SysRole sysRole : list)
        {
        	ZtreeNew ztree = new ZtreeNew();
            ztree.setId(sysRole.getRoleId()+"");
            ztree.setpId("0");
            if (sysRole.getNoId() != null ) {
            	ztree.setChecked(true);
			}
            ztree.setName(transMenuName(sysRole));
            ztree.setTitle(sysRole.getRoleName());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    public String transMenuName(SysRole sysRole)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(sysRole.getRoleName());
        return sb.toString();
    }

	/**
	 * 修改公告
	 */
	@GetMapping("/edit/{noticeId}")
	public String edit(@PathVariable("noticeId") Long noticeId, ModelMap mmap) {
		mmap.put("notice", noticeService.selectNoticeById(noticeId));
		return prefix + "/edit";
	}
	@GetMapping("/edit2/{noticeId}")
	public String edit2(@PathVariable("noticeId") Long noticeId, ModelMap mmap) {
		mmap.put("notice", noticeService.selectNoticeById(noticeId));
		return prefix + "/edit2";
	}
	@GetMapping("/editN/{noticeId}")
	public String editN(@PathVariable("noticeId") Integer msgId, ModelMap mmap) {
		Long userId = ShiroUtils.getUserId();
		
		SysUserMsg selectSysUserMsgById = sysUserMsgMapper.selectSysUserMsgById(msgId);
		selectSysUserMsgById.setIsRead("2");
		sysUserMsgMapper.updateSysUserMsg(selectSysUserMsgById);
		SysNotice selectNoticeById = new SysNotice();
		if (selectSysUserMsgById.getNoticeId() != null) {
			selectNoticeById = noticeService.selectNoticeById(new Long(selectSysUserMsgById.getNoticeId()));
		}else{
			selectNoticeById.setNoticeContent(selectSysUserMsgById.getContent());
			selectNoticeById.setNoticeTitle("库存预警");
		}
		
		
		mmap.put("notice", selectNoticeById);
		return prefix + "/editN";
	}

	/**
	 * 修改保存公告
	 */
	@RequiresPermissions("system:notice:edit")
	@Log(title = "通知公告", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(SysNotice notice) {
		notice.setUpdateBy(ShiroUtils.getLoginName());
		List<SysUserMsg> updateNotice = noticeService.updateNotice(notice);
		if (updateNotice != null && updateNotice.size() > 0) {
			for (SysUserMsg sysUserMsg : updateNotice) {
				myWebSocketHandler.sendInfo(sysUserMsg.getUserId().toString(), "有公告了");;
			}
		}
		return toAjax(1);
	}

	/**
	 * 删除公告
	 */
	@RequiresPermissions("system:notice:remove")
	@Log(title = "通知公告", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		return toAjax(noticeService.deleteNoticeByIds(ids));
	}
}
